package cn.gok.controller;

import cn.gok.pojo.Practice;
import cn.gok.service.CheckService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.gok.tool.DynamicDataSource;
import cn.gok.tool.Tool;
import com.alibaba.druid.pool.DruidDataSource;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/check/")
public class CheckController {

    @Autowired
    private CheckService checkService;

//    根据选择试卷，校验题目做的是否正确
    @RequestMapping("/judge")
    @ResponseBody
    public JSONObject judge(@RequestBody JSONObject json){
        JSONObject res=new JSONObject();
////        更换数据源
        Tool tool=new Tool();
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(tool.tourl(json.getString("ip"),json.getString("ports"),json.getString("databases")));
        druidDataSource.setUsername(json.getString("username"));
        druidDataSource.setPassword(json.getString("password"));

        //DruidDataSource 2487行
        druidDataSource.setBreakAfterAcquireFailure(true);
        //前端快速响应
        druidDataSource.setFailFast(true);
        druidDataSource.setMaxWait(10000);
        druidDataSource.setValidationQuery("select 1 from dual");
        druidDataSource.setValidationQueryTimeout(5000);
        DynamicDataSource.dataSourcesMap.put("dbkey", druidDataSource);
        DynamicDataSource.setDataSource("dbkey");
//        业务代码
        List<Practice> list=tool.toList(json.getJSONArray("data"));
        Map map=tool.fen(json.getString("questions"));
        String msg=checkService.judge(list,map);
        res.put("msg",msg);

//        恢复默认数据源
        DynamicDataSource.clear();
//        记录日志
        checkService.judge_log(json.getString("user"),json.getString("questions"),msg,list.get(0).getTitle());

        return res;
    }

    @RequestMapping("/selof")
    @ResponseBody
    public JSONObject selof(@RequestBody JSONObject json){
        JSONObject res=new JSONObject();
        res.put("data",checkService.selof(json.getString("query")));
        return res;
    }

    @RequestMapping("/del")
    @ResponseBody
    public JSONObject del(@RequestBody JSONObject json){
        JSONObject res=new JSONObject();
        res.put("code",checkService.del(json.getInteger("id")));
        return res;
    }
}
